package com.jonluo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jonluo.common.utils.EnvVariable;
import com.jonluo.common.utils.PageUtils;
import com.jonluo.common.utils.R;
import com.jonluo.common.utils.UuidUtils;
import com.jonluo.entity.RoleDeptEntity;
import com.jonluo.entity.RoleEntity;
import com.jonluo.entity.RoleMenuEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 * @author com.jonluo
 * Date 2017/9/15
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController extends AbstractController {

	@Autowired
	RestTemplate restTemplate;
	@Autowired
	EnvVariable envVariable;
	
	/**
	 * 角色列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:role:list")
	public R list(@RequestParam Map<String, Object> params){
		JSONObject json = new JSONObject();
		JSONObject para = new JSONObject();
		json.put("page",params.get("page"));
		json.put("limit",params.get("limit"));
		para.put("roleName",params.get("roleName"));
		json.put("params",para);
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/role/getAll",json, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if ( 0 == resultMap.getInteger("code")){
			PageUtils pageUtil = new PageUtils(resultMap.getJSONArray("data"),resultMap.getInteger("total"),json.getInteger("limit"),json.getInteger("page") );
			return R.ok().put("page", pageUtil);
		}else {
			return R.ok().put("page",  new PageUtils());
		}
	}
	
	/**
	 * 角色列表
	 */
	@RequestMapping("/select")
	@RequiresPermissions("sys:role:select")
	public R select(){
		List<RoleEntity> list = null;
		JSONObject json = new JSONObject();
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/role/getAll",json, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		list = JSONArray.parseArray(resultMap.getJSONArray("data").toJSONString(),RoleEntity.class);
		return R.ok().put("list", list);
	}
	
	/**
	 * 角色信息
	 */
	@RequestMapping("/info/{roleId}")
	@RequiresPermissions("sys:role:info")
	public R info(@PathVariable("roleId") String roleId){
		RoleEntity role = null;
		String resultJson = restTemplate.getForEntity(envVariable.getBaseUrl()+"/role/getById/"+roleId, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if ( 0 == resultMap.getInteger("code")){
			role = resultMap.getObject("data",RoleEntity.class);
		}else {
			role = new RoleEntity();
		}
		//查询角色对应的菜单
		JSONObject json = new JSONObject();
		JSONObject para = new JSONObject();
		para.put("roleId",roleId);
		json.put("params",para);
		resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleMenu/getAll",json, String.class).getBody();
		resultMap = JSONObject.parseObject(resultJson);
		List<RoleMenuEntity> roleMenulist = JSONArray.parseArray(resultMap.getJSONArray("data").toJSONString(),RoleMenuEntity.class);
		List<String> menuIdList = new ArrayList<String>();
		for (RoleMenuEntity roleMenu:roleMenulist){
			menuIdList.add(roleMenu.getMenuId());
		}
		role.setMenuIdList(menuIdList);

		//查询角色对应的部门
		resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleDept/getAll",json, String.class).getBody();
		resultMap = JSONObject.parseObject(resultJson);
		List<RoleDeptEntity> roleDeptlist = JSONArray.parseArray(resultMap.getJSONArray("data").toJSONString(), RoleDeptEntity.class);
		List<String> deptIdList = new ArrayList<String>();
		for (RoleDeptEntity roleDept:roleDeptlist){
			deptIdList.add(roleDept.getDeptId());
		}
		role.setDeptIdList(deptIdList);
		
		return R.ok().put("role", role);
	}
	
	/**
	 * 保存角色
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sys:role:save")
	public R save(@RequestBody RoleEntity role){
		role.setRoleId(UuidUtils.getUUID("role"));
		role.setCreateTime(new Date());
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/role/add",role, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		int i = roleDeptAndRoleMenuSaveOrUpdate(role.getRoleId(), role.getDeptIdList(), role.getMenuIdList());
		if(0 == resultMap.getInteger("code") && i == 0){
			return R.ok("success");
		}else {
			return R.error("fail");
		}

	}
	
	/**
	 * 修改角色
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sys:role:update")
	public R update(@RequestBody RoleEntity role){
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/role/update",role, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		int i = roleDeptAndRoleMenuSaveOrUpdate(role.getRoleId(), role.getDeptIdList(), role.getMenuIdList());
		if(0 == resultMap.getInteger("code") && i == 0){
			return R.ok("success");
		}else {
			return R.error("fail");
		}
	}
	
	/**
	 * 删除角色
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:role:delete")
	public R delete(@RequestBody String[] roleIds){
		JSONObject json = new JSONObject();
		json.put("roleIds", StringUtils.join(roleIds, ","));
		String rResultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/role/deleteByIds",json, String.class).getBody();
		//删除角色与部门关系
		restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleDept/deleteByRoleIds",json, String.class);
		//删除角色与菜单关系
		restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleMenu/deleteByRoleIdsOrMenuIds",json, String.class);
		//删除角色与用户关系
		restTemplate.postForEntity(envVariable.getBaseUrl()+"/userRole/deleteByUserIdsOrRoleIds",json, String.class);

		JSONObject resultMap = JSONObject.parseObject(rResultJson);
		if(0 == resultMap.getInteger("code")){
			return R.ok("success");
		}else {
			return R.error("fail");
		}
	}


	public int roleDeptAndRoleMenuSaveOrUpdate(String roleId, List<String> deptIdList, List<String> menuIdList) {

		JSONObject json = new JSONObject();
		json.put("roleIds", roleId);
		//先删除角色与部门关系
		String dResultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleDept/deleteByRoleIds",json, String.class).getBody();
		JSONObject dResultMap = JSONObject.parseObject(dResultJson);
		//先删除角色与菜单关系
		String mResultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleMenu/deleteByRoleIdsOrMenuIds",json, String.class).getBody();
		JSONObject mResultMap = JSONObject.parseObject(mResultJson);

		if(deptIdList.size() > 0 && dResultMap.getInteger("code") == 0){
			//保存角色与部门关系
			List<RoleDeptEntity> list = new ArrayList<RoleDeptEntity>();
			RoleDeptEntity roleDept= null;
			for (int i = 0; i < deptIdList.size(); i++){
				roleDept = new RoleDeptEntity();
				roleDept.setId(UuidUtils.getUUID("roleDept"));
				roleDept.setRoleId(roleId);
				roleDept.setDeptId(deptIdList.get(i));
				list.add(roleDept);
			}
			json.put("list",list);
			dResultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleDept/addBatch",json, String.class).getBody();
			dResultMap = JSONObject.parseObject(dResultJson);

		}
		if(menuIdList.size() > 0&& mResultMap.getInteger("code") == 0){
			//保存角色与菜单关系
			List<RoleMenuEntity> list = new ArrayList<RoleMenuEntity>();
			RoleMenuEntity roleMenu= null;
			for (int i = 0; i < menuIdList.size(); i++){
				roleMenu= new RoleMenuEntity();
				roleMenu.setId(UuidUtils.getUUID("roleMenu"));
				roleMenu.setRoleId(roleId);
				roleMenu.setMenuId(menuIdList.get(i));
				list.add(roleMenu);
			}
			json.put("list",list);
			mResultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/roleMenu/addBatch",json, String.class).getBody();
			mResultMap = JSONObject.parseObject(mResultJson);
		}

		return  dResultMap.getInteger("code") + mResultMap.getInteger("code");

	}

}
